import 'package:flutter/material.dart';
import 'package:flutter_shop/helpers/Api.dart';
import 'package:flutter_shop/helpers/HttpProxy.dart';
import 'package:flutter_shop/models/categroyModel.dart';

class CategoryProvider with ChangeNotifier {
  String categoryId;
  String categorySubId;
  List<BxMallSubDto> childCategoryList = [];

  List<CategoryBigModel> _leftMenuList = [];

  List<CategoryGoodsModel> categoryGoodsList = [];

  get leftMenuList => this._leftMenuList;

  setChildCategory(List<BxMallSubDto> list) {
    this.childCategoryList = list;
    this.categoryId = list[0].mallCategoryId;
    this.categorySubId = list[0].mallSubId;
    notifyListeners();
    this._updateGoodList();
  }

  setCategoryGoodsList(List<CategoryGoodsModel> list) {
    this.categoryGoodsList = list;
  }

  _updateGoodList() {
    this.getGoodList().then((result) {
      print(result);
      this.categoryGoodsList = this._convertDataToModel(result);
      notifyListeners();
    });
  }

  Future<List> getGoodList([int page = 1]) async {
    if (categoryId == null) {
      return [];
    }
    try {
      HttpBaseResult res = await Api.getCategoryGoodsList(
          page, this.categoryId, this.categorySubId);
      if (res.code == "0") {
        if (res.data == null) {
          return [];
        }
        return res.data;
      }
      print(res.message);
      return [];
    } catch (e) {
      print(e);
      return [];
    }
  }

  List<CategoryGoodsModel> _convertDataToModel(dynamic data) {
    return (data as List).cast().map((item) {
      return CategoryGoodsModel.fromJson(item);
    }).toList();
  }

  setId(categorySubId) {
    this.categorySubId = categorySubId;
    this._updateGoodList();
  }

  appendGoodList(dynamic data) {
    this.categoryGoodsList.addAll(this._convertDataToModel(data));
    notifyListeners();
  }

  setLeftMenuList(List<CategoryBigModel> list) {
    this._leftMenuList = list;
    this.childCategoryList = list[0].bxMallSubDto;
    this.categoryId = list[0].mallCategoryId;
    this.categorySubId = this.childCategoryList[0].mallSubId;
    notifyListeners();
    this._updateGoodList();
  }
}
